package org.hepeng.workx.spring.boot.error;

import org.hepeng.workx.service.RestServiceCallResult;
import org.hepeng.workx.service.error.ServerError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author he peng
 */

@RestController
@RequestMapping("${server.error.path:${error.path:/error}}")
public class GlobalErrorController implements ErrorController {

    @Autowired
    private RouteLocator routeLocator;

    @Autowired
    private Environment env;

    @Autowired
    private ServerProperties serverProperties;

    @Autowired
    private ErrorAttributes errorAttributes;


    @RequestMapping
    public ResponseEntity<RestServiceCallResult> error(
            NativeWebRequest request , HttpServletResponse response) {
        ErrorBody errorBody = ErrorBody.newErrorBody(request , this.errorAttributes , this.env , this.routeLocator);
        RestServiceCallResult callResult = RestServiceCallResult.restBuilder()
                .error(ServerError.SERVER_ERROR)
                .data(errorBody)
                .build();

        return ResponseEntity.status(getStatus(request.getNativeRequest(HttpServletRequest.class))).body(callResult);
    }

    protected HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        }
        catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }

    @Override
    public String getErrorPath() {
        return serverProperties.getError().getPath();
    }
}
